package com.agileai.portal.controller.mobile;

import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataMap;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.common.HttpClientHelper;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.mobile.AngularWidgetManage;
import com.agileai.portal.bizmoduler.mobile.AppModuleConfigManage;
import com.agileai.portal.driver.AttributeKeys;
import com.agileai.portal.driver.mobile.AngularWidget;
import com.agileai.portal.driver.model.MenuBar;
import com.agileai.portal.driver.model.MenuItem;
import com.agileai.portal.driver.model.Page;
import com.agileai.portal.driver.model.Theme;
import com.agileai.portal.driver.service.DriverConfiguration;
import com.agileai.portal.driver.service.PortalConfigService;
import com.agileai.portal.extend.ExtendConsts.ExtendPropertyKeys;
import com.agileai.portal.extend.ExtendConsts.TempPropertyKeys;
import com.agileai.portal.extend.mobile.MobileHelper;
import com.agileai.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class MobileDataProviderHandler extends BaseHandler {
	private PortalConfigService portalConfigService = null;
	
	@PageAction
	public ViewRenderer retreiveCtrlFile(DataParam param){
		String menuBarCode = param.get("menuBarCode");
		String menuCode = param.get("menuCode");
		menuCode = menuCode.substring(0,menuCode.length()-3);
		
		ServletContext servletContext = this.dispatchServlet.getServletContext();
		this.portalConfigService = getPortalConfigService(servletContext);
		MenuBar menuBar = portalConfigService.getMenuBar(menuBarCode);
		MenuItem menuItem = menuBar.getMenuItemCodeMap().get(menuCode);
		
		StringBuffer resultText = new StringBuffer();

		User user = (User)this.getUser();
		MobileHelper mobileHelper = new MobileHelper(menuBar, user);
		String pageId = menuItem.getPageId();
		Page page = portalConfigService.getPage(pageId);
		List<AngularWidget> widgetList = mobileHelper.getAngularWidgetList(page);
      	List<ControlModel> controlModels = this.getControllerFiles(mobileHelper,menuBar,menuItem, widgetList);

      	for (int j=0;j < controlModels.size();j++){
      		resultText.append("\r\n");
      		
      		ControlModel controlModel = controlModels.get(j);
      		String tempMenuCode = controlModel.getMenuCode();
      		String tempWidgetCode = controlModel.getWidgetCode();
      		String controllerFilePath = controlModel.getFilePath();
      		
      		String widgetControlJs = this.getWidgetControlJs(tempMenuCode, tempWidgetCode, controllerFilePath);
      		resultText.append(widgetControlJs);
      	}
		resultText.append("\r\n");

		return new AjaxRenderer(resultText.toString());
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private String getWidgetControlJs(String menuCode,String widgetCode,String controllerFilePath){
		String responseText = null;
		String cacheKey = menuCode+"!"+ widgetCode;
		synchronized (cacheKey) {
			if (!AngularWidgetManage.ControllerFileContents.containsKey(cacheKey)){
				HttpClientHelper httpClientHelper = new HttpClientHelper();
				String serverName = this.request.getServletContext().getInitParameter("serverName");
				String controllerFileURL = serverName + controllerFilePath;
				String contrllerFileContent = httpClientHelper.retrieveGetReponseText(controllerFileURL);
				
				if (contrllerFileContent != null){
					StringWriter writer = new StringWriter();
					HashMap varRoot = new HashMap();
					varRoot.put("menuCode",menuCode);
					varRoot.put("widgetCode",widgetCode);
					
					this.parseContent(varRoot, contrllerFileContent, writer);
					
					String replacedContent = writer.toString();
					
					AngularWidgetManage.ControllerFileContents.put(cacheKey, replacedContent);					
				}
			}			
		}
		responseText = AngularWidgetManage.ControllerFileContents.get(cacheKey);
		
		return responseText ;
	}	
	
	private List<ControlModel> getControllerFiles(MobileHelper mobileHelper,MenuBar menuBar,MenuItem menuItem,List<AngularWidget> widgetList){
		List<ControlModel> result = new ArrayList<ControlModel>();
		String menuCode = menuItem.getCode();
		JSONObject properties = menuItem.getProperties();
		if (properties != null && properties.has(MobileHelper.PageCtrlFileKey)){
			try {
				String filePath = properties.getString(MobileHelper.PageCtrlFileKey);
				
				ControlModel pageControlModel = new ControlModel();
				pageControlModel.setMenuCode(menuCode);
				pageControlModel.setWidgetCode(menuCode+"-"+MobileHelper.PageKeyName);
				pageControlModel.setFilePath(filePath);
				
				result.add(pageControlModel);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		for (int i=0;i < widgetList.size();i++){
			AngularWidget widget = widgetList.get(i);
			String filePath = widget.getControllerFile();
			String widgetCode = widget.getCode();
			
			ControlModel widgetControlModel = new ControlModel();
			widgetControlModel.setMenuCode(menuCode);
			widgetControlModel.setWidgetCode(widgetCode);
			widgetControlModel.setFilePath(filePath);
			
			result.add(widgetControlModel);
		}
		
		if (properties != null && properties.has("modals")){
			try {
				LinkedHashMap<String, MenuItem> menuMap =  menuBar.getAllMenuItemMap();
				String modals = properties.getString("modals");
				String[] modalMenuCodes = modals.split(",");
				if (modalMenuCodes != null && modalMenuCodes.length > 0){
					for (int j =0; j < modalMenuCodes.length;j++){
						String modalMenuCode = modalMenuCodes[j];
						MenuItem curMenuItem = menuMap.get(modalMenuCode);
						if (curMenuItem != null){
							String curPageId = curMenuItem.getPageId();
							Page curPage = portalConfigService.getPage(curPageId);
							List<AngularWidget> curWidgetList = mobileHelper.getAngularWidgetList(curPage);
							
							for (int i=0;i < curWidgetList.size();i++){
								AngularWidget widget = curWidgetList.get(i);
								String filePath = widget.getControllerFile();
								String widgetCode = widget.getCode();
								
								ControlModel widgetControlModel = new ControlModel();
								widgetControlModel.setMenuCode(menuCode);
								widgetControlModel.setWidgetCode(widgetCode);
								widgetControlModel.setFilePath(filePath);
								
								result.add(widgetControlModel);
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		if (properties != null && properties.has("popovers")){
			try {
				LinkedHashMap<String, MenuItem> menuMap =  menuBar.getAllMenuItemMap();
				String popovers = properties.getString("popovers");
				String[] popoverMenuCodes = popovers.split(",");
				if (popoverMenuCodes != null && popoverMenuCodes.length > 0){
					for (int j =0; j < popoverMenuCodes.length;j++){
						String popoverMenuCode = popoverMenuCodes[j];
						MenuItem curMenuItem = menuMap.get(popoverMenuCode);
						if (curMenuItem != null){
							String curPageId = curMenuItem.getPageId();
							Page curPage = portalConfigService.getPage(curPageId);
							List<AngularWidget> curWidgetList = mobileHelper.getAngularWidgetList(curPage);
							
							for (int i=0;i < curWidgetList.size();i++){
								AngularWidget widget = curWidgetList.get(i);
								String filePath = widget.getControllerFile();
								String widgetCode = widget.getCode();
								
								ControlModel widgetControlModel = new ControlModel();
								widgetControlModel.setMenuCode(menuCode);
								widgetControlModel.setWidgetCode(widgetCode);
								widgetControlModel.setFilePath(filePath);
								
								result.add(widgetControlModel);
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
		
		if (properties != null && properties.has("popups")){
			try {
				LinkedHashMap<String, MenuItem> menuMap =  menuBar.getAllMenuItemMap();
				String popups = properties.getString("popups");
				String[] popoverMenuCodes = popups.split(",");
				if (popoverMenuCodes != null && popoverMenuCodes.length > 0){
					for (int j =0; j < popoverMenuCodes.length;j++){
						String popoverMenuCode = popoverMenuCodes[j];
						MenuItem curMenuItem = menuMap.get(popoverMenuCode);
						if (curMenuItem != null){
							String curPageId = curMenuItem.getPageId();
							Page curPage = portalConfigService.getPage(curPageId);
							List<AngularWidget> curWidgetList = mobileHelper.getAngularWidgetList(curPage);
							
							for (int i=0;i < curWidgetList.size();i++){
								AngularWidget widget = curWidgetList.get(i);
								String filePath = widget.getControllerFile();
								String widgetCode = widget.getCode();

								
								ControlModel widgetControlModel = new ControlModel();
								widgetControlModel.setMenuCode(menuCode);
								widgetControlModel.setWidgetCode(widgetCode);
								widgetControlModel.setFilePath(filePath);
								
								result.add(widgetControlModel);
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
		return result;
	}	
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@PageAction
	public ViewRenderer retreiveTmplFile(DataParam param){
		String responseText = "";
		String menuBarCode = param.get("menuBarCode");
		String menuCode = param.get("menuCode");
		String widgetCode = param.get("widgetCode");
		
		String cacheKey = menuCode+"!"+ widgetCode;
		synchronized (cacheKey) {
			if (!AngularWidgetManage.TemplateFileContents.containsKey(cacheKey)){
				
				ServletContext servletContext = this.dispatchServlet.getServletContext();
				this.portalConfigService = getPortalConfigService(servletContext);
				MenuBar menuBar = portalConfigService.getMenuBar(menuBarCode);
				MenuItem tempMenuItem = menuBar.getMenuItemCodeMap().get(menuCode);
				
				String curPageId = tempMenuItem.getPageId();
				Page curPage = portalConfigService.getPage(curPageId);
				User user = (User)this.getUser();
				MobileHelper mobileHelper = new MobileHelper(menuBar, user);
				
				AngularWidget angularWidget = mobileHelper.getPageAngularWidget(curPage, widgetCode);
				
				
				HttpClientHelper httpClientHelper = new HttpClientHelper();
				String serverName = this.request.getServletContext().getInitParameter("serverName");
				String templateFileURL = serverName + angularWidget.getTemplateFile();
				String templateFileContent = httpClientHelper.retrieveGetReponseText(templateFileURL);
				
				if (templateFileContent != null){
					StringWriter writer = new StringWriter();
					HashMap varRoot = new HashMap();
					varRoot.put("menuCode",menuCode);
					varRoot.put("widgetCode",widgetCode);
					
					this.parseContent(varRoot, templateFileContent, writer);
					
					String replacedContent = writer.toString();
					
					AngularWidgetManage.TemplateFileContents.put(cacheKey, replacedContent);					
				}
			}			
		}
		responseText = AngularWidgetManage.TemplateFileContents.get(cacheKey);
		return new AjaxRenderer(responseText);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@PageAction
	public ViewRenderer retrieveAppJs(DataParam param){
		String responseText = "";
		String menuBarCode = param.get("menuBarCode");
		String appJsFilePath = getAppJsFileURL(menuBarCode);
		HttpClientHelper httpClientHelper = new HttpClientHelper();
		String serverName = this.request.getServletContext().getInitParameter("serverName");
		String appJsFileURL = serverName + appJsFilePath;
		String appJsFileContent = httpClientHelper.retrieveGetReponseText(appJsFileURL);
		if (appJsFileContent != null){
			StringWriter writer = new StringWriter();
			HashMap varRoot = new HashMap();
			varRoot.put("menuBarCode",menuBarCode);
			this.parseContent(varRoot, appJsFileContent, writer);
			responseText = writer.toString();
		}
		return new AjaxRenderer(responseText);
	}
	
	private PortalConfigService getPortalConfigService(ServletContext servletContext){
		if (portalConfigService == null){
			DriverConfiguration driverConfiguration = (DriverConfiguration)servletContext.getAttribute(AttributeKeys.DRIVER_CONFIG);
			portalConfigService = driverConfiguration.getPortalConfigService();	
		}
		return portalConfigService;
	}
	
	private String getAppJsFileURL(String menuBarCode){
		String result = null;
		ServletContext servletContext = dispatchServlet.getServletConfig().getServletContext();
		String contextRealPath = servletContext.getRealPath("");
		File contextFile = new File(contextRealPath);
		String parentAbsolutePath = contextFile.getParentFile().getAbsolutePath();
		
		PortalConfigService portalConfigService = getPortalConfigService(servletContext);
		MenuBar menuBar = portalConfigService.getMenuBar(menuBarCode);
		String themeId = menuBar.getThemeId();
		Theme theme = portalConfigService.getTheme(themeId);
		String themPageURL = theme.getThemePageURL();
		
		String resourseFilePath = parentAbsolutePath+File.separator+"portal"+File.separator+"themes" + File.separator+themPageURL;
		File themeFile = new File(resourseFilePath);
		String appJsFilePath = themeFile.getParentFile().getAbsolutePath() + File.separator+"js" + File.separator+"app.js";
		result = appJsFilePath.substring(parentAbsolutePath.length());
		result = result.replace("\\", "/");
		return result;
	}	
	
	
	private static List<DataRow> getAuthedRecords(User user,List<DataRow> tempRecords){
		List<DataRow> result = new ArrayList<DataRow>();
		for (int i=0;i < tempRecords.size();i++){
			DataRow row = tempRecords.get(i);
			String appModuleId = row.stringValue("AC_ID");
			if (containResouce(appModuleId,user) || "admin".equals(user.getUserCode())){
				result.add(row);
			}
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	private static boolean containResouce(String appModuleId,User user){
		boolean result = false;
		List<String> appModuleResource =  new ArrayList<String>();
		appModuleResource =  (List<String>) user.getExtendProperties().get(ExtendPropertyKeys.AppModuleIdList);
		if(appModuleResource.contains(appModuleId)){
			result = true;
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public static List<AppModule> getAppModuleList(User user){
		List<AppModule> result = new ArrayList<AppModule>();
		List<AppModule> tempAppModules = new ArrayList<AppModule>();
		try {
			DataParam queryParam = new DataParam("USER_ID",user.getUserId());
			AppModuleConfigManage appModuleConfigManage = (AppModuleConfigManage)BeanFactory.instance().getBean("appModuleConfigManageService");
			DataRow record =  appModuleConfigManage.getUserAppConfig(queryParam);
			String appConfig = record.getString("APP_CONFIG");
			JSONObject jsonAppConfig = new JSONObject();
			String moduleIds = "";
			if(StringUtil.isNotNullNotEmpty(appConfig)){
				jsonAppConfig = new JSONObject(appConfig);
				if(appConfig.contains("moduleIds")){
					moduleIds = jsonAppConfig.getString("moduleIds");
				}
			}
			if(StringUtil.isNullOrEmpty(moduleIds)){
				if(user.getTempProperties().containsKey(TempPropertyKeys.AppModules)){
					tempAppModules = (List<AppModule>)user.getTempProperties().get(TempPropertyKeys.AppModules);
				}else{
					DataParam param = new DataParam();
					List<DataRow> tempRecords =  appModuleConfigManage.findRecords(param);
					//权限过滤
					List<DataRow> records = getAuthedRecords(user,tempRecords);
					for(int i=0;i<records.size();i++){
						DataRow row = records.get(i);
						AppModule appModule = new AppModule();
						appModule.setId(row.getString("AC_ID"));
						appModule.setName(row.getString("AC_NAME"));
						appModule.setCss(row.getString("AC_CSS"));
						String appMethod = row.getString("AC_METHOD");
						if(StringUtil.isNotNullNotEmpty(appMethod) && appMethod.startsWith("{")){
							JSONObject methodJson = new JSONObject(appMethod);
							appModule.setMenthodType(methodJson.getString("key"));
							appModule.setMethod(methodJson.getString("val"));
						}else{
							appModule.setMenthodType("href");
							appModule.setMethod("");
						}
						appModule.setVaild(row.getString("AC_VAILD"));
						appModule.setGroup(row.getString("AC_GROUP"));
						appModule.setSort(row.getInt("AC_SORT"));
						tempAppModules.add(i, appModule);
					}
					user.getTempProperties().put(TempPropertyKeys.AppModules,tempAppModules);
				}
			}else{
				if(user.getTempProperties().containsKey(TempPropertyKeys.AppModules)){
					tempAppModules = (List<AppModule>)user.getTempProperties().get(TempPropertyKeys.AppModules);
				}else{
					JSONArray jsonArray =new JSONArray(moduleIds);
					for(int i=0;i<jsonArray.length();i++){
						String appModuleId = (String) jsonArray.get(i);
						AppModule appModule = appModuleConfigManage.retrieveppModuleRecord(appModuleId);
						if(appModule != null){
							tempAppModules.add(appModule);
						}
					}
					user.getTempProperties().put(TempPropertyKeys.AppModules,tempAppModules);
				}
			}
			List<String> existsKeyList = new ArrayList<String>();
//			List<AppModule> allAppModules = MobileDataProviderHandler.findAllAppModuleList(user);
//			MobileDataProviderHandler.converKeyToList(allAppModules, existsKeyList);
			for(int i=0;i<tempAppModules.size();i++){
				AppModule appModule = tempAppModules.get(i);
				String appModuleId = appModule.getId();
				if (!existsKeyList.contains(appModuleId)){
					result.add(appModule);
					existsKeyList.add(appModuleId);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}	

	public static List<AppModule> findAllAppModuleList(User user){
		List<AppModule> appModules = new ArrayList<AppModule>();
		try {
			AppModuleConfigManage appModuleConfigManage = (AppModuleConfigManage)BeanFactory.instance().getBean("appModuleConfigManageService");
			DataParam param = new DataParam();
			List<DataRow> tempRecords =  appModuleConfigManage.findRecords(param);
			List<DataRow> records = getAuthedRecords(user,tempRecords);
			for(int i=0;i<records.size();i++){
				DataRow row = records.get(i);
				AppModule appModule = new AppModule();
				appModule.setId(row.getString("AC_ID"));
				appModule.setName(row.getString("AC_NAME"));
				appModule.setCss(row.getString("AC_CSS"));
				appModule.setMethod(row.getString("AC_METHOD"));
				appModule.setVaild(row.getString("AC_VAILD"));
				appModule.setGroup(row.getString("AC_GROUP"));
				appModule.setSort(row.getInt("AC_SORT"));
				appModules.add(i, appModule);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return appModules;
	}
	
	@PageAction
	public ViewRenderer findAppModuleList(DataParam param){
		String responseText = "";
		try {
			User user = (User) this.getUser();
			List<AppModule> appModules = getAppModuleList(user);
			JSONArray jsonArray = new JSONArray();
			int appModulesSize = appModules.size();
			int loopNums = getLoopNums(appModulesSize);
			for(int i=0;i<appModulesSize;i++){
				AppModule appModule = appModules.get(i);
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("id", appModule.getId());
				jsonObject.put("text", appModule.getName());
				jsonObject.put("css", appModule.getCss());
				jsonObject.put("methodText", appModule.getMethod());
				jsonObject.put("methodType", appModule.getMenthodType());
				jsonArray.put(jsonObject);
			}
			JSONArray extraJsonArray = new JSONArray();
			for (int i = 0; i < loopNums; i++) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("id", "");
				jsonObject.put("text", "");
				jsonObject.put("css", "");
				jsonObject.put("methodText", "#");
				jsonObject.put("methodType", "href");
				extraJsonArray.put(jsonObject);
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("moduleList", jsonArray);
			jsonObject.put("extraList", extraJsonArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}

	private int getLoopNums(int appModulesSize){
		int result = 0;
		if(appModulesSize>3){
			int extraSize = appModulesSize%4;
			result = 4-(extraSize+1);
		}else{
			result = 4-(appModulesSize+1);
		}
		return result;
	}
	
	@PageAction
	public ViewRenderer findToChooseAppModuleList(DataParam param){
		String responseText = "";
		try {
			User user = (User) this.getUser();
			List<AppModule> appModules = getAppModuleList(user);
			List<String> existsKeyList = new ArrayList<String>();
			converKeysToList(appModules, existsKeyList);
			
			List<AppModule> allAppModules = MobileDataProviderHandler.findAllAppModuleList(user);
			JSONArray jsonArray = new JSONArray();
			
			List<AppModule> waitSelectAppModuleList = new ArrayList<AppModule>();
			for(int i=0; i < allAppModules.size();i++){
				AppModule appModule = allAppModules.get(i);
				String appModuleId = appModule.getId();
				if (!existsKeyList.contains(appModuleId)){
					waitSelectAppModuleList.add(appModule);
				}
			}
			
			for(int i=0;i < waitSelectAppModuleList.size();i++){
				AppModule appModule = waitSelectAppModuleList.get(i);
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("id", appModule.getId());
				jsonObject.put("text", appModule.getName());
				jsonArray.put(jsonObject);
			}
			
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("toChooseModuleList", jsonArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer saveThemeColor(DataParam param){
		String responseText = FAIL;
    	try {
    		String inputString = this.getInputString();
			JSONObject jsonObject = new JSONObject(inputString);
			String themeColor =  jsonObject.get("color").toString();
			
			User user = (User) getUser();
			DataParam queryParam = new DataParam("USER_ID",user.getUserId());
			AppModuleConfigManage appModuleConfigManage = (AppModuleConfigManage)BeanFactory.instance().getBean("appModuleConfigManageService");
			DataRow record =  appModuleConfigManage.getUserAppConfig(queryParam);
			String appConfig = record.getString("APP_CONFIG");
			JSONObject jsonAppConfig = null;
			if (StringUtil.isNotNullNotEmpty(appConfig)){
				jsonAppConfig = new JSONObject(appConfig);	
			}else{
				jsonAppConfig = new JSONObject();
			}
			jsonAppConfig.put("themeColor",themeColor);
			appModuleConfigManage.saveAppModuleConfig(jsonAppConfig.toString(),user.getUserId());
			
			responseText = SUCCESS;
		} catch (JSONException e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer getMobileTheme(DataParam param) {
		String responseText = "";
		try {
			FormSelect formSelect = FormSelectFactory.create("MOBILE_THEME");

			JSONArray jsonArray = new JSONArray();
			for (int i=0;i < formSelect.size();i++){
				DataMap dataMap = (DataMap)formSelect.get(String.valueOf(i+1));
				String key = dataMap.getString(FormSelect.DEF_KEY_COLUMN_NAME);
				String value = dataMap.getString(FormSelect.DEF_VALUE_COLUMN_NAME);
				
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("text",value);
				jsonObject.put("value",key);
				jsonArray.put(jsonObject);
			}
			
			responseText = jsonArray.toString();
		} catch (JSONException e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer initMobileTheme(DataParam param) {
		String responseText = "";
		try {
			User user = (User) getUser();
			DataParam queryParam = new DataParam("USER_ID",user.getUserId());
			AppModuleConfigManage appModuleConfigManage = (AppModuleConfigManage)BeanFactory.instance().getBean("appModuleConfigManageService");
			DataRow record =  appModuleConfigManage.getUserAppConfig(queryParam);
			String appConfig = record.getString("APP_CONFIG");
			String themeColor = "";
			JSONObject jsonAppConfig = new JSONObject();
			if(StringUtil.isNotNullNotEmpty(appConfig)){
				jsonAppConfig = new JSONObject(appConfig);
				if(appConfig.contains("themeColor")){
					themeColor = jsonAppConfig.getString("themeColor");
				}else{
					themeColor = "default";
				}
			}else{
				themeColor = "default";
			}
			responseText = themeColor;
		} catch (JSONException e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public static String getThemeColor(User user) throws JSONException{
		String responseText = "";
		DataParam queryParam = new DataParam("USER_ID",user.getUserId());
		AppModuleConfigManage appModuleConfigManage = (AppModuleConfigManage)BeanFactory.instance().getBean("appModuleConfigManageService");
		DataRow record =  appModuleConfigManage.getUserAppConfig(queryParam);
		String appConfig = record.getString("APP_CONFIG");
		String themeColor = "";
		JSONObject jsonAppConfig = new JSONObject();
		if(StringUtil.isNotNullNotEmpty(appConfig)){
			jsonAppConfig = new JSONObject(appConfig);
			if(appConfig.contains("themeColor")){
				themeColor = jsonAppConfig.getString("themeColor");
			}else{
				themeColor = "default";
			}
		}else{
			themeColor = "default";
		}
				
		FormSelect formSelect = FormSelectFactory.create("MOBILE_THEME");
		responseText = formSelect.getDescription(themeColor);
		
		return responseText;
	}
	

	private void converKeysToList(List<AppModule> appModules,List<String> existsKeyList){
		for (int i=0;i < appModules.size();i++){
			AppModule appModule = appModules.get(i);
			String key = appModule.getId();
			existsKeyList.add(key);
		}
	}
	
	@PageAction
	public ViewRenderer isFirstOrLastModule(DataParam param){
		String responseText = FAIL;
		try {
			String moduleId = param.getString("moduleId");
			User user = (User) this.getUser();
			List<AppModule> appModules = getAppModuleList(user);
			if(moduleId.equals(appModules.get(0).getId())){
				responseText = "top";
			}
			if(moduleId.equals(appModules.get(appModules.size()-1).getId())){
				responseText = "bottom";
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer mobileSaveAppModule(DataParam param){
		String responseText = null;
		try {
			JSONObject responseJson = new JSONObject();
			responseJson.put("text",FAIL);
			responseJson.put("msg",SUCCESS);
			User user = (User) this.getUser();
			String mark = param.getString("mark");
			String receiveList = this.getInputString();
			AppModuleConfigManage appModuleConfigManage = lookupService(AppModuleConfigManage.class);
			String userCode = user.getUserCode();
			DataParam queryParam = new DataParam("USER_CODE",userCode);
			DataRow record =  appModuleConfigManage.getUserAppConfig(queryParam);
			String appConfig = record.getString("APP_CONFIG");
			String moduleIds = null;
			JSONObject jsonAppConfig = new JSONObject();
			if(StringUtil.isNotNullNotEmpty(appConfig)){
				jsonAppConfig = new JSONObject(appConfig);
				if(appConfig.contains("moduleIds")){
					moduleIds = jsonAppConfig.getString("moduleIds");
				}
			}
			JSONArray appArray = new JSONArray();
			List<AppModule> appModules = getAppModuleList(user);
			if(StringUtil.isNotNullNotEmpty(moduleIds)){
				appArray = new JSONArray(moduleIds);
			}else{
				for (int i = 0; i < appModules.size(); i++) {
					AppModule appModule = appModules.get(i); 
					appArray.put(i, appModule.getId());
				}
			}
			if("selected".equals(mark)){
				JSONArray jsonreceive = new JSONArray(receiveList);
				for(int i=0;i<jsonreceive.length();i++){
					JSONObject jsonObject = jsonreceive.getJSONObject(i);
					String id = jsonObject.getString("id");
					appArray.put(appArray.length(), id);
				}
				String appModuleConfig = appArray.toString();
				jsonAppConfig.put("moduleIds", appModuleConfig);
				appModuleConfigManage.saveAppModuleConfig(jsonAppConfig.toString(),user.getUserId());
			}else if("delete".equals(mark)){
				String id = param.getString("id");
				ArrayList<String> delList = new ArrayList<String>(); 
				delList.add(id);
				ArrayList<String> list = new ArrayList<String>(); 
				if (appArray != null) { 
					 for (int i=0;i<appArray.length();i++){ 
						 list.add(appArray.get(i).toString());
					 } 
					 list.removeAll(delList);
					 JSONArray jsArray = new JSONArray(list);
					 jsonAppConfig.put("moduleIds", jsArray);
					 appModuleConfigManage.saveAppModuleConfig(jsonAppConfig.toString(),user.getUserId());
				}
			}else if("upMove".equals(mark)){
				String id = param.getString("id");
				int curIndex = 0;
				String tempId = null;
				if (appArray != null) { 
					 for (int i=0;i<appArray.length();i++){ 
						 String appModuleId = (String) appArray.get(i);
						 if(id.equals(appModuleId)){
							 curIndex = i;
							 break;
						 }
					 } 
					 if(curIndex > 0){
						 String beforeId = appArray.getString(curIndex-1);
						 tempId = beforeId;
						 appArray.put(curIndex-1, id);
						 appArray.put(curIndex, tempId);
					 }else{
						 responseJson.put("msg",FAIL);
					 }
					 jsonAppConfig.put("moduleIds", appArray);
					 appModuleConfigManage.saveAppModuleConfig(jsonAppConfig.toString(),user.getUserId());
				}
			}else if("upMoveTop".equals(mark)){
				String id = param.getString("id");
				int curIndex = 0;
				for (int i=0;i<appArray.length();i++){ 
					 String appModuleId = (String) appArray.get(i);
					 if(id.equals(appModuleId)){
						 curIndex = i;
						 break;
					 }
				} 
				ArrayList<String> tempList = new ArrayList<String>();
				if (appArray != null) {
					 for (int i = 0; i < appArray.length(); i++) {
						tempList.add(i, appArray.getString(i));
					 }
					 if(curIndex > 0){
						tempList.remove(curIndex);
						tempList.add(0, id);
					 }else{
						 responseJson.put("msg",FAIL);
					 }
					 JSONArray saveJsonArray = new JSONArray(tempList);
					 jsonAppConfig.put("moduleIds", saveJsonArray);
					 appModuleConfigManage.saveAppModuleConfig(jsonAppConfig.toString(),user.getUserId());
				}
			}else if("downMove".equals(mark)){
				String id = param.getString("id");
				int curIndex = 0;
				String tempId = null;
				if (appArray != null) { 
					 for (int i=0;i<appArray.length();i++){ 
						 String appModuleId = (String) appArray.get(i);
						 if(id.equals(appModuleId)){
							 curIndex = i;
							 break;
						 }
					 } 
					 if(curIndex < appArray.length()-1){
						 String afterId = appArray.getString(curIndex+1);
						 tempId = afterId;
						 appArray.put(curIndex+1, id);
						 appArray.put(curIndex, tempId);
					 }else{
						 responseJson.put("msg",FAIL);
					 }
					 jsonAppConfig.put("moduleIds", appArray);
					 appModuleConfigManage.saveAppModuleConfig(jsonAppConfig.toString(),user.getUserId());
				}
			}else if("downMoveBottom".equals(mark)){
				String id = param.getString("id");
				int curIndex = 0;
				for (int i=0;i<appArray.length();i++){ 
					 String appModuleId = (String) appArray.get(i);
					 if(id.equals(appModuleId)){
						 curIndex = i;
						 break;
					 }
				} 
				ArrayList<String> tempList = new ArrayList<String>();
				if (appArray != null) {
					 for (int i = 0; i < appArray.length(); i++) {
						tempList.add(i, appArray.getString(i));
					 }
					 if(curIndex < appArray.length()-1){
						tempList.remove(curIndex);
						tempList.add(id);
					 }else{
						 responseJson.put("msg",FAIL);
					 }
					 JSONArray saveJsonArray = new JSONArray(tempList);
					 jsonAppConfig.put("moduleIds", saveJsonArray);
					 appModuleConfigManage.saveAppModuleConfig(jsonAppConfig.toString(),user.getUserId());
				}
			}
			user.getTempProperties().remove(TempPropertyKeys.AppModules);
			responseJson.put("text",SUCCESS);
			responseText = responseJson.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@SuppressWarnings("rawtypes")
	private void parseContent(Map root,String template,StringWriter writer) {
		String encoding = "utf-8";
		try {
        	Configuration cfg = new Configuration();
        	cfg.setTemplateLoader(new StringTemplateLoader(template));  
        	cfg.setEncoding(Locale.getDefault(), encoding);
            cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        	Template temp = cfg.getTemplate("");
        	temp.setEncoding(encoding);
            temp.process(root, writer);
            writer.flush();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	
	protected static void removeCache(String widgetCode){
		Iterator<String> iter = AngularWidgetManage.ControllerFileContents.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			if (key.endsWith("!"+widgetCode)){
				AngularWidgetManage.ControllerFileContents.remove(key);
				AngularWidgetManage.TemplateFileContents.remove(key);
				break;
			}
		}
	}
	
	protected static void removeWidgetCache(String widgetId){
		if (AngularWidgetManage.AngularWidgetCache.containsKey(widgetId)){
			AngularWidgetManage.AngularWidgetCache.remove(widgetId);
		}
	}	
	
	protected static void removeCaches(){
		AngularWidgetManage.ControllerFileContents.clear();
		AngularWidgetManage.TemplateFileContents.clear();
		AngularWidgetManage.AngularWidgetCache.clear();
		AppModuleConfigManage.AppModuleCache.clear();
	}
	
	private class ControlModel{
		private String menuCode = null;
		private String widgetCode = null;
		private String filePath = null;
		public String getMenuCode() {
			return menuCode;
		}
		public void setMenuCode(String menuCode) {
			this.menuCode = menuCode;
		}
		public String getWidgetCode() {
			return widgetCode;
		}
		public void setWidgetCode(String widgetCode) {
			this.widgetCode = widgetCode;
		}
		public String getFilePath() {
			return filePath;
		}
		public void setFilePath(String filePath) {
			this.filePath = filePath;
		}
	}		
}